package com.doubao.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doubao.common.result.Result;
import com.doubao.device.dto.TagDTO;
import com.doubao.device.dto.request.CreateTagRequest;
import com.doubao.device.entity.SmartDeviceTag;
import com.doubao.device.entity.SmartDeviceTagRelation;
import com.doubao.device.mapper.SmartDeviceTagMapper;
import com.doubao.device.mapper.SmartDeviceTagRelationMapper;
import com.doubao.device.service.SmartDeviceTagService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 智能体标签服务实现类
 */
@Service
@RequiredArgsConstructor
public class SmartDeviceTagServiceImpl extends ServiceImpl<SmartDeviceTagMapper, SmartDeviceTag> implements SmartDeviceTagService {

    private final SmartDeviceTagRelationMapper relationMapper;

    @Override
    public Result<TagDTO> createTag(CreateTagRequest request) {
        // 检查标签名称是否已存在
        LambdaQueryWrapper<SmartDeviceTag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SmartDeviceTag::getName, request.getName());
        
        SmartDeviceTag existingTag = baseMapper.selectOne(queryWrapper);
        if (existingTag != null) {
            return Result.failed("标签名称已存在");
        }
        
        // 创建新标签
        SmartDeviceTag tag = new SmartDeviceTag();
        tag.setName(request.getName());
        tag.setType(request.getType());
        tag.setUsedCount(0); // 初始使用次数为0
        tag.setCreatedAt(LocalDateTime.now());
        tag.setUpdatedAt(LocalDateTime.now());
        
        // 保存标签
        boolean saved = save(tag);
        if (!saved) {
            return Result.failed("创建标签失败");
        }
        
        // 转换为DTO返回
        TagDTO tagDTO = new TagDTO();
        BeanUtils.copyProperties(tag, tagDTO);
        
        return Result.success(tagDTO);
    }

    @Override
    public Result<Void> deleteTag(Long tagId) {
        // 检查标签是否存在
        SmartDeviceTag tag = getById(tagId);
        if (tag == null) {
            return Result.failed("标签不存在");
        }
        
        // 删除标签关联
        relationMapper.deleteByTagId(tagId);
        
        // 删除标签
        boolean removed = removeById(tagId);
        if (!removed) {
            return Result.failed("删除标签失败");
        }
        
        return Result.success();
    }

    @Override
    public Result<TagDTO> getTagDetail(Long tagId) {
        SmartDeviceTag tag = getById(tagId);
        if (tag == null) {
            return Result.failed("标签不存在");
        }
        
        TagDTO tagDTO = new TagDTO();
        BeanUtils.copyProperties(tag, tagDTO);
        
        return Result.success(tagDTO);
    }

    @Override
    public Result<List<TagDTO>> getAllTags() {
        List<SmartDeviceTag> tags = list();
        List<TagDTO> tagDTOs = tags.stream()
                .map(tag -> {
                    TagDTO dto = new TagDTO();
                    BeanUtils.copyProperties(tag, dto);
                    return dto;
                })
                .collect(Collectors.toList());
        
        return Result.success(tagDTOs);
    }


    @Override
    public Result<List<TagDTO>> getHotTags(Integer limit) {
        LambdaQueryWrapper<SmartDeviceTag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(SmartDeviceTag::getUsedCount)
                .last("LIMIT " + limit);

        List<SmartDeviceTag> tags = list(queryWrapper);
        List<TagDTO> tagDTOs = tags.stream()
                .map(tag -> {
                    TagDTO dto = new TagDTO();
                    BeanUtils.copyProperties(tag, dto);
                    return dto;
                })
                .collect(Collectors.toList());

        return Result.success(tagDTOs);
    }

    @Override
    public Result<List<TagDTO>> getTagsByType(String type) {
        LambdaQueryWrapper<SmartDeviceTag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SmartDeviceTag::getType, type);

        List<SmartDeviceTag> tags = list(queryWrapper);
        List<TagDTO> tagDTOs = tags.stream()
                .map(tag -> {
                    TagDTO dto = new TagDTO();
                    BeanUtils.copyProperties(tag, dto);
                    return dto;
                })
                .collect(Collectors.toList());

        return Result.success(tagDTOs);
    }

    @Override
    public Result<List<TagDTO>> getDeviceTags(Long deviceId) {
        // 查询设备关联的标签ID
        LambdaQueryWrapper<SmartDeviceTagRelation> relationQuery = new LambdaQueryWrapper<>();
        relationQuery.eq(SmartDeviceTagRelation::getDeviceId, deviceId);

        List<SmartDeviceTagRelation> relations = relationMapper.selectList(relationQuery);
        if (relations.isEmpty()) {
            return Result.success(new ArrayList<>());
        }

        List<Long> tagIds = relations.stream()
                .map(SmartDeviceTagRelation::getTagId)
                .collect(Collectors.toList());

        // 查询标签详情
        List<SmartDeviceTag> tags = listByIds(tagIds);
        List<TagDTO> tagDTOs = tags.stream()
                .map(tag -> {
                    TagDTO dto = new TagDTO();
                    BeanUtils.copyProperties(tag, dto);
                    return dto;
                })
                .collect(Collectors.toList());

        return Result.success(tagDTOs);
    }

    @Override
    @Transactional
    public Result<List<Long>> batchCreateTags(List<String> tagNames, String type) {
        if (tagNames == null || tagNames.isEmpty()) {
            return Result.success(new ArrayList<>());
        }

        List<Long> tagIds = new ArrayList<>();
        
        for (String name : tagNames) {
            // 检查标签是否已存在
            LambdaQueryWrapper<SmartDeviceTag> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SmartDeviceTag::getName, name);
            
            SmartDeviceTag existingTag = getOne(queryWrapper);
            if (existingTag != null) {
                tagIds.add(existingTag.getId());
                continue;
            }
            
            // 创建新标签
            SmartDeviceTag tag = new SmartDeviceTag();
            tag.setName(name);
            tag.setType(type);
            tag.setUsedCount(0);
            tag.setCreatedAt(LocalDateTime.now());
            tag.setUpdatedAt(LocalDateTime.now());
            
            save(tag);
            tagIds.add(tag.getId());
        }
        
        return Result.success(tagIds);
    }

    @Override
    @Transactional
    public Result<Void> addDeviceTags(Long deviceId, List<Long> tagIds) {
        if (tagIds == null || tagIds.isEmpty()) {
            return Result.success();
        }

        for (Long tagId : tagIds) {
            // 检查关联是否已存在
            LambdaQueryWrapper<SmartDeviceTagRelation> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SmartDeviceTagRelation::getDeviceId, deviceId)
                    .eq(SmartDeviceTagRelation::getTagId, tagId);

            Long count = relationMapper.selectCount(queryWrapper); // 修改这里
            if (count > 0) {
                continue;
            }

            // 创建新关联
            SmartDeviceTagRelation relation = new SmartDeviceTagRelation();
            relation.setDeviceId(deviceId);
            relation.setTagId(tagId);
            relation.setCreatedAt(LocalDateTime.now());

            relationMapper.insert(relation);

            // 增加标签使用次数
            increaseUsedCount(tagId);
        }

        return Result.success();
    }


    @Override
    @Transactional
    public Result<Void> removeDeviceTags(Long deviceId, List<Long> tagIds) {
        if (tagIds == null || tagIds.isEmpty()) {
            return Result.success();
        }
        
        for (Long tagId : tagIds) {
            LambdaQueryWrapper<SmartDeviceTagRelation> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SmartDeviceTagRelation::getDeviceId, deviceId)
                    .eq(SmartDeviceTagRelation::getTagId, tagId);
            
            relationMapper.delete(queryWrapper);
        }
        
        return Result.success();
    }

    @Override
    @Transactional
    public Result<Void> updateDeviceTags(Long deviceId, List<Long> tagIds) {
        // 先删除所有关联
        relationMapper.deleteByDeviceId(deviceId);
        
        // 如果没有新标签，直接返回
        if (tagIds == null || tagIds.isEmpty()) {
            return Result.success();
        }
        
        // 添加新关联
        return addDeviceTags(deviceId, tagIds);
    }

    @Override
    public Result<Void> increaseUsedCount(Long tagId) {
        SmartDeviceTag tag = getById(tagId);
        if (tag == null) {
            return Result.failed("标签不存在");
        }
        
        tag.setUsedCount(tag.getUsedCount() + 1);
        tag.setUpdatedAt(LocalDateTime.now());
        
        boolean updated = updateById(tag);
        if (!updated) {
            return Result.failed("更新标签使用次数失败");
        }
        
        return Result.success();
    }

    @Override
    public SmartDeviceTagRelationMapper getRelationMapper() {
        return relationMapper;
    }
}